package in.muton.edushare.poll.answers;

import in.muton.edushare.pages.EduShareBasePage;
import in.muton.edushare.wicket.models.CayenneList;

import java.util.Collections;
import java.util.List;

import org.apache.wicket.behavior.AttributeAppender;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;

import com.edushare.common.dao.UserPollDAO;
import com.edushare.common.vo.PollOptions;
import com.edushare.common.vo.PollQuestions;

public class DropdownAnswer extends AnswerBase {
	private static final long serialVersionUID = 5014570623166898284L;

	public DropdownAnswer(String id, IModel<PollQuestions> model,
			EduShareBasePage page) {
		super(id, model, page);
		add(new Label("totalAnswers", new PropertyModel<Integer>(this,
				"totalAnswers")));
		List<PollOptions> poL = getQuestionModel().getObject().getOptions();
		Collections.sort(poL);
		CayenneList<PollOptions> poList = new CayenneList<PollOptions>(poL);

		add(new ListView<IModel<PollOptions>>("optionList", poList) {
			private static final long serialVersionUID = 438796580049950609L;

			@Override
			protected void populateItem(ListItem<IModel<PollOptions>> arg0) {
				final PollOptions po = arg0.getModelObject().getObject();
				arg0.add(new Label("optionName", po.getOptionString()));

				String chosenBy = ""
						+ new UserPollDAO(getORMInterface())
								.getResponsesByOption(po);
				chosenBy += "/" + getTotalAnswers();

				arg0.add(new Label("chosenBy", chosenBy));
				WebMarkupContainer wmc = new WebMarkupContainer("barGraph");
				arg0.add(wmc);
				wmc.add(new AttributeAppender("style", new Model<String>() {
					private static final long serialVersionUID = -3640929235459473758L;

					@Override
					public String getObject() {
						int chosenBy = new UserPollDAO(getORMInterface())
								.getResponsesByOption(po);
						if (getTotalAnswers() == 0)
							return "width:0px";
						int pixWidth = (chosenBy * 100) / getTotalAnswers();
						return "width:" + pixWidth + "px";
					}
				}, ";"));
			}
		});
	}

	public Integer getTotalAnswers() {
		return getQuestionModel().getObject().getAnswers().size();
	}
}
